package com.onenine.app.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.sdk.android.manager.OssManager;
import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.ImageAddAdapter;
import com.onenine.app.event.PostPublicEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.event.VideoFinishEvent;
import com.onenine.app.listener.LastItemUnDragAndSwipeCallback;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.view.VideoPlayLayout;
import com.onenine.app.view.popwin.MediaPopWindow;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.SwitchButton;
import com.onenine.chat.emoji.Constants;
import com.onenine.chat.emoji.EmojiBean;
import com.onenine.chat.emoji.EmojiView;
import com.onenine.chat.emoji.EmoticonsKeyboardUtils;
import com.onenine.chat.emoji.data.EmoticonEntity;
import com.onenine.chat.emoji.listener.EmoticonClickListener;
import com.onenine.chat.emoji.widget.EmoticonsEditText;
import com.onenine.chat.util.SimpleCommonUtils;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.common.util.SoftKeyboardListener;
import com.onenine.dialog.CommonTextDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import cn.jzvd.Jzvd;

/**
 * 发贴
 */
public class PostPublishActivity extends UploadImageActivity implements View.OnTouchListener, EmoticonClickListener
        , View.OnClickListener, BaseQuickAdapter.OnItemClickListener, SoftKeyboardListener.OnSoftKeyBoardChangeListener
        , OssManager.Callback, BaseQuickAdapter.OnItemChildClickListener {

    private EmoticonsEditText mEdtEmoji;
    private EmojiView mEmojiView;
    private RecyclerView mRecyclerView;
    private BaseItemDraggableAdapter mImageAdapter;
    private SwitchButton mBtnSync;
    private boolean mKeyboardShow;
    private VideoPlayLayout mVideoPlay;
    private int mPvType;//0图片1视频

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_post_publish;
    }

    @Override
    protected void compressImageSuccess(File file) {
        mPvType = DataType.POST_IMAGE_TYPE;
        mImageAdapter.notifyItemInserted(0);
        toggleMultiMediaView();
    }

    @Override
    protected void uploadImagesSuccess(String imageUrls) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (mPvType == DataType.POST_IMAGE_TYPE) {
            //图片
            if (position == mImagePaths.size() - 1) {
                KeyboardUtils.hideSoftInput(this);
                new MediaPopWindow(this
                        , MediaPopWindow.IMAGE_TYPE, this).showPopWindow();
            } else if (position >= 0) {
                ArrayList<String> urls = new ArrayList<>(mImageAdapter.getData());
                urls.remove(urls.size() - 1);
                BrowserImageActivity.launchActivity(this, urls, position);
            }
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mImageAdapter.remove(position);
        mRecyclerView.requestLayout();
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setLeftTitle(R.string.cancel);
        mToolbar.setRightTitleBackground(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG), true);
        mToolbar.setRightTitle(R.string.next_step);
        mToolbar.setCenterTitle(R.string.publish_post);
        mEdtEmoji = findViewById(R.id.edt_content);
        mEmojiView = findViewById(R.id.ev_emoji_bar);
        mVideoPlay = findViewById(R.id.vv_play);
        mBtnSync = findViewById(R.id.sb_sync);
        mBtnSync.setCheckedColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mEdtEmoji.setOnTouchListener(this);
        mToolbar.setOnRightClickListener(this);
        mToolbar.setOnLeftClickListener(this);
        findViewById(R.id.btn_photo).setOnClickListener(this);
        findViewById(R.id.btn_video).setOnClickListener(this);
        findViewById(R.id.btn_emoji).setOnClickListener(this);
        SoftKeyboardListener.setListener(this, this);
    }

    @Override
    protected void initData() {
        super.initData();
        mImagePaths.add(UploadImageActivity.IMAGE_ADD);
        SimpleCommonUtils.initEmoticonsEditText(mEdtEmoji);
        mEmojiView.setAdapter(SimpleCommonUtils
                .getCommonAdapter(this, this));
        mRecyclerView = findViewById(R.id.rv_image);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mImageAdapter = new ImageAddAdapter(mImagePaths, (AppConfig.SCREEN_WIDTH - SizeUtils.dp2px(72)) / 3);
        mRecyclerView.setAdapter(mImageAdapter);
        mImageAdapter.setOnItemClickListener(this);
        mImageAdapter.setOnItemChildClickListener(this);
        mImageAdapter.enableDragItem(new LastItemUnDragAndSwipeCallback(mRecyclerView, mImageAdapter).getItemTouchHelper());
        onTouch(mEdtEmoji, null);
    }

    private void showEmojiLayout() {
        mEmojiView.setVisibility(View.VISIBLE);
    }

    private boolean isEmojiLayoutVisible() {
        return mEmojiView.getVisibility() == View.VISIBLE;
    }

    private void dismissEmojiLayout() {
        mEmojiView.setVisibility(View.GONE);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.edt_content) {
            if (!mEdtEmoji.isFocused()) {
                mEdtEmoji.setFocusable(true);
                mEdtEmoji.setFocusableInTouchMode(true);
            }
        }
        if (isEmojiLayoutVisible()) {
            dismissEmojiLayout();
        }
        return false;
    }

    @Override
    public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {
        if (isDelBtn) {
            SimpleCommonUtils.delClick(mEdtEmoji);
        } else {
            if (o == null) {
                return;
            }
            if (actionType == Constants.EMOTICON_CLICK_BIGIMAGE) {
            } else {
                String content = null;
                if (o instanceof EmojiBean) {
                    content = ((EmojiBean) o).emoji;
                } else if (o instanceof EmoticonEntity) {
                    content = ((EmoticonEntity) o).getContent();
                }

                if (TextUtils.isEmpty(content)) {
                    return;
                }
                int index = mEdtEmoji.getSelectionStart();
                Editable editable = mEdtEmoji.getText();
                editable.insert(index, content);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left_title:
                //关闭
                if (!backQuitHint()) {
                    finish();
                }
                break;
            case R.id.tv_right_title:
                //发贴
                if (!verifyNextStep()) {
                    return;
                }
                //组装下一步数据
                PostPublicEvent event = new PostPublicEvent();
                event.postDesc = mEdtEmoji.getText().toString().trim();
                event.isSync = mBtnSync.isChecked();
                event.pvType = mPvType;
                event.pvList = new ArrayList<>();
                if (mPvType == DataType.POST_IMAGE_TYPE) {
                    event.pvList.addAll(mImagePaths);
                    event.pvList.remove(IMAGE_ADD);
                } else {
                    event.pvList.add(mVideoPlay.getFirstFramePath());
                    event.pvList.add(mVideoPlay.getVideoUrl());
                }
                ActivityUtils.startActivity(this, SelectCoterieActivity.class);
                EventBus.getDefault().postSticky(event);
                break;
            case R.id.btn_photo:
                //图片
                KeyboardUtils.hideSoftInput(this);
                new MediaPopWindow(this
                        , MediaPopWindow.IMAGE_TYPE, this).showPopWindow();
                break;
            case R.id.btn_video:
                //视频选择或拍摄
                KeyboardUtils.hideSoftInput(this);
                new MediaPopWindow(this
                        , MediaPopWindow.VIDEO_TYPE, this).showPopWindow();
                break;
            case R.id.btn_emoji:
                //表情
                if (isEmojiLayoutVisible()) {
                    dismissEmojiLayout();
                } else if (mKeyboardShow) {
                    EmoticonsKeyboardUtils.closeSoftKeyboard(mEdtEmoji);
                    mEdtEmoji.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showEmojiLayout();
                        }
                    }, 100);
                } else {
                    showEmojiLayout();
                }
                break;
        }
    }

    /**
     * 无图
     *
     * @return
     */
    private boolean isNoImage() {
        return mImagePaths.size() <= 1;
    }

    /**
     * 校验参数
     *
     * @return
     */
    private boolean verifyNextStep() {
        if (TextUtils.isEmpty(mEdtEmoji.getText().toString().trim()) &&
                mPvType == DataType.POST_IMAGE_TYPE && isNoImage()) {
            Toasty.showNormal(R.string.publish_post_empty);
            return false;
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(VideoFinishEvent event) {
        mPvType = DataType.POST_VIDEO_TYPE;
        toggleMultiMediaView();
        mVideoPlay.playVideo(event.firstFramePicPath, event.videoPath);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (DataType.REFRESH_POST_PUBLISH_SUCCESS == event.type) {
            finish();
        }
    }

    /**
     * 图片和视频界面切换
     */
    private void toggleMultiMediaView() {
        if (mPvType == DataType.POST_IMAGE_TYPE) {
            if (mRecyclerView.getVisibility() != View.VISIBLE) {
                mRecyclerView.setVisibility(View.VISIBLE);
            }
            if (mVideoPlay.getVisibility() == View.VISIBLE) {
                mVideoPlay.setVisibility(View.GONE);
            }
        } else {
            if (mRecyclerView.getVisibility() == View.VISIBLE) {
                mRecyclerView.setVisibility(View.GONE);
                mImagePaths.clear();
                mImagePaths.add(IMAGE_ADD);
                mImageAdapter.notifyDataSetChanged();
            }
            if (mVideoPlay.getVisibility() != View.VISIBLE) {
                mVideoPlay.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void keyBoardShow(int height) {
        mKeyboardShow = true;
        mEmojiView.getLayoutParams().height = height;
    }

    @Override
    public void keyBoardHide(int height) {
        mKeyboardShow = false;
    }

    @Override
    protected void finishSelectVideo(VideoFinishEvent event) {
        onEvent(event);
    }

    @Override
    protected int getMaxImageCount() {
        return AppConfig.IMAGE_MAX_POST;
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        } else if (isEmojiLayoutVisible()) {
            dismissEmojiLayout();
        } else if (mKeyboardShow) {
            EmoticonsKeyboardUtils.closeSoftKeyboard(mEdtEmoji);
        } else if (!backQuitHint()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPvType == DataType.POST_VIDEO_TYPE) {
            Jzvd.releaseAllVideos();
        }
    }

    /**
     * 返回退出提示
     *
     * @return
     */
    private boolean backQuitHint() {
        if (!"".equals(mEdtEmoji.getText().toString().trim())
                || !isNoImage() || !TextUtils.isEmpty(mVideoPlay.getVideoUrl())) {
            CommonTextDialog.Builder builder = new CommonTextDialog.Builder(this);
            builder.setText(getResources().getString(R.string.abandon_publish_post));
            builder.setOnOkClickListener((dialog, which) -> {
                super.finish();
                overridePendingTransition(0, R.anim.slide_out_bottom);
            }).builder().show();
            return true;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
